package com.gitee.wsl.common.more.ext.glide

import android.content.Context
import android.graphics.Bitmap
import android.os.Looper
import android.text.TextUtils
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.load.engine.cache.DiskCache
import com.bumptech.glide.load.engine.cache.ExternalCacheDiskCacheFactory
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.gitee.wsl.android.ext.ApplicationInit
import com.gitee.wsl.common.more.ext.glide.cache.DiskLruPartitionCacheFactory
import com.gitee.wsl.android.ui.ext.ApplicationScope
import com.gitee.wsl.android.ext.ApplicationInit.application
import com.gitee.wsl.jvm.ext.store.formatDirSize
import timber.log.Timber
import java.io.File

val globalGlide:Glide = Glide.get(application)

object GlideConfig{
    fun applyDiskLruPartitionCache(context: Context, builder: GlideBuilder) {
        //builder.setMemoryCache(new LruResourceCache(10 * 1024 * 1024));
        DiskLruPartitionCacheFactory.addFactory(
            DiskLruPartitionCacheFactory.DISK_LRU_PARTITION_DOWNLOAD_PICTURE,
            context,
            DiskLruPartitionCacheFactory.DISK_LRU_PARTITION_DOWNLOAD_PICTURE,
            DiskCache.Factory.DEFAULT_DISK_CACHE_SIZE
        )
        builder.setDiskCache(DiskLruPartitionCacheFactory.getInstance(context))
    }
} 

object GlideExt {

    val bitmapPool by lazy {
        globalGlide.bitmapPool
    }

    @JvmStatic
    fun createBitmap(width: Int, height: Int, config: Bitmap.Config): Bitmap {
        return bitmapPool.get(width, height, config)
    }

    /**
     * 清除图片磁盘缓存
     */
    fun clearImageDiskCache() {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                Thread { globalGlide.clearDiskCache() }.start()
            } else {
                globalGlide.clearDiskCache()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 清除图片内存缓存
     */
    fun clearImageMemoryCache(context: Context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行
                Timber.d("before glide memory alloc:" + getCacheSize(context))
                globalGlide.clearMemory()
                Timber.d("before glide memory alloc:" + getCacheSize(context))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 清除图片所有缓存
     */
    fun clearImageAllCache(context: Context) {
        clearImageDiskCache()
        clearImageMemoryCache(context)
        val imageExternalCatchDir = context.externalCacheDir.toString() + ExternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR
        deleteFolderFile(imageExternalCatchDir, true)
    }

    /**
     * 获取Glide造成的缓存大小
     *
     * @return CacheSize
     */
    fun getCacheSize(context: Context): String {
        try {
            return File(context.cacheDir.toString() + "/" + InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR).formatDirSize
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    /**
     * 获取指定文件夹内所有文件大小的和
     *
     * @param file file
     * @return size
     * @throws Exception
     */
    @Throws(Exception::class)
    private fun getFolderSize(file: File): Long {
        var size: Long = 0
        try {
            val fileList = file.listFiles()
            for (aFileList in fileList) {
                size = if (aFileList.isDirectory) {
                    size + getFolderSize(aFileList)
                } else {
                    size + aFileList.length()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return size
    }

    /**
     * 删除指定目录下的文件，这里用于缓存的删除
     *
     * @param filePath filePath
     * @param deleteThisPath deleteThisPath
     */
    private fun deleteFolderFile(filePath: String, deleteThisPath: Boolean) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                val file = File(filePath)
                if (file.isDirectory) {
                    val files = file.listFiles()
                    for (file1 in files) {
                        deleteFolderFile(file1.absolutePath, true)
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory) {
                        file.delete()
                    } else {
                        if (file.listFiles()?.isEmpty() == true) {
                            file.delete()
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    
}

fun ApplicationScope.useGlideImageLoader(){
    ApplicationInit.imageLoader = GlideImageLoader()
}

/**
 * author ：Peakmain
 * createTime：2020/9/9
 * mail:2726449200@qq.com
 * describe：recyclerview在空闲的时候加载图片
 */
class ImageRecyclerScrollListener() : RecyclerView.OnScrollListener() {
    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
        super.onScrollStateChanged(recyclerView, newState)
        //空闲的时候加载图片
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            ApplicationInit.imageLoader.resumeRequest()
        } else {
            ApplicationInit.imageLoader.pauseRequest()
        }
    }
}